import { BizKfExtraProColumnType } from '@/components';
import { history } from '@umijs/max';
import { Divider, Layout, message, Space, Tag, Typography } from 'antd';
import { KfPagingTablePagePropsAction, useBackendEnum, convertKfEnumsToProTableValueEnum, KfModal, KfPagingTablePage } from 'kf-web-library';
import { now } from 'moment';
import qs from 'query-string';
import React, { useEffect, useRef, useState } from 'react';
import { useLocation } from 'umi';
import AuthList from './components/AuthList';
import GroupTree from './components/GroupTree';
import QuickUserForm from './components/QuickForm';
import './style.less';
import * as API from '@/services';
import { useAccess } from '@@/exports';

type Entity = API.User;
type EntityPageQueryParams = API.UserPageQueryParams;
const entityTypeName = '用户';

interface EntityTableListProps {}

/**
 * 用户列表
 */
const EntityTableList: React.FC<EntityTableListProps> = (props) => {
  const location = useLocation();
  const actionRef = useRef<KfPagingTablePagePropsAction<Entity, EntityPageQueryParams>>();
  const [groupId, setGroupId] = useState<number | string | undefined>(undefined);
  const { enumDict, getBackendEnum } = useBackendEnum();
  const access = useAccess();

  useEffect(() => {
    const searchObj = qs.parse(location.search as any) as any;
    setGroupId(searchObj.groupId);
  }, [location.search]);

  return (
    <Layout>
      <Layout.Sider theme={'light'} collapsible={false} width={280} className={'kf-group-tree-sider'}>
        <GroupTree
          selectedKey={groupId}
          onSelect={(selectedKeys) => {
            history.push(
              `?${qs.stringify({
                ...qs.parse(location.search),
                groupId: selectedKeys,
                timestamp: now(),
              })}`,
            );
          }}
        />
      </Layout.Sider>
      <Layout.Content>
        <KfPagingTablePage<Entity, EntityPageQueryParams, BizKfExtraProColumnType>
          actionRef={actionRef}
          entityTypeName={entityTypeName}
          //wrapper={({ children: dom }) => <>{dom}</>}
          //hasPageHeader={false}
          pagingQuery={(p) =>
            API.queryUsers({
              ...p,
              type: ['SYSTEM', 'OPERATE'],
            })
          }
          opActionsDef={{
            single: {
              deleteOne: (record) => {
                KfModal.deleteConfirm(record.id as string, () => {
                  API.deleteUser(record.id!).then((res) => {
                    if (res.flag) {
                      message.info('删除成功');
                      actionRef.current?.reload();
                    }
                  });
                });
              },
              enableOne: (record) => {
                KfModal.confirm('启用', record.nickname, () => {
                  API.enableUser(record.id!).then((res) => {
                    if (res.flag) {
                      message.info('启用成功');
                      actionRef.current?.reload();
                    }
                  });
                });
              },
              disableOne: (record) => {
                KfModal.confirm('停用', record.nickname, () => {
                  API.disableUser(record.id!).then((res) => {
                    if (res.flag) {
                      message.info('停用成功');
                      actionRef.current?.reload();
                    }
                  });
                });
              },
            },
            /*multi: {
                deleteMultiple: (records) => {
                    KfModal.batchDeleteConfirm(records.length, () => {
                        service.deleteUsers(records.map((r) => r.id!)).then((res) => {
                            if (res.flag) {
                                message.info('批量删除成功');
                                actionRef.current?.reload();
                            }
                        });
                    });
                },
            }*/
          }}
          opFloatingsDef={{
            noargs: {
              createModal: () => ({
                title: `新建${entityTypeName}`,
                content: <QuickUserForm formType={'create'} />,
              }),

              /*importModal: () => ({
                  title: `导入${entityTypeName}`,
                  content: <KfStaticTemplateDataImport
                      getImportTemplateFileUrlPath={"/api/v1/user/import?_import_template_export_=1"}
                      importDataServiceUrlPath={"/api/v1/user/import"}
                      importDataServiceMethod={"POST"}/>
              }),*/
            },
            single: {
              modifyModal: (record) => ({
                title: `编辑${entityTypeName}`,
                content: <QuickUserForm formType={'modify'} bizId={record.id} />,
              }),
              viewModal: (record) => ({
                title: `查看${entityTypeName}`,
                content: <QuickUserForm formType={'view'} bizId={record.id} />,
              }),
              authListModal: (record) => ({
                title: `编辑${entityTypeName}账号信息`,
                content: <AuthList bizId={record.id} />,
              }),
            },
          }}
          proTable={{
            search: {
              defaultCollapsed: false,
            },
            tableBarActions: (action, rows) => {
              return [
                /* <Button type="primary"
                         onClick={() => actionRef.current?.openModal.noargs?.importModal()}>
                     <UploadOutlined/> 导入
                 </Button>*/
              ];
            },
          }}
          columns={[
            {
              title: '关键字',
              dataIndex: 'searchText',
              sorter: false,
              hideInTable: true,
              hideInForm: true,
              fieldProps: {
                placeholder: '模糊检索昵称和登录账号',
              },
            },
            {
              title: '角色',
              dataIndex: 'roleNameOrCode',
              sorter: false,
              hideInTable: true,
              hideInForm: true,
              fieldProps: {
                placeholder: '模糊检索角色名称或编码',
              },
            },
            /*{
                title: '类型',
                width: 100,
                dataIndex: nameof<Entity>((x) => x.type),
                sorter: false,
                hideInSearch: true,
                ellipsis: true,
                valueEnum: convertKfEnumsToProTableValueEnum(enumDict['UserType']),
                fixed: 'left',
            },*/
            {
              title: '登录账号',
              width: 120,
              dataIndex: nameof<Entity>((x) => x.auths),
              sorter: false,
              hideInSearch: true,
              ellipsis: true,
              renderText: (_, record) => {
                return record.auths?.map((auth) => auth.identifier).join(', ');
              },
            },
            {
              title: '昵称',
              width: 200,
              dataIndex: nameof<Entity>((x) => x.nickname),
              sorter: false,
              hideInSearch: true,
              ellipsis: true,
            },
            {
              title: '类型',
              width: 160,
              dataIndex: nameof<Entity>((x) => x.type),
              sorter: false,
              hideInSearch: false,
              ellipsis: true,
              kfValueEnum: "UserType",
            },
            {
              title: '角色',
              dataIndex: nameof<Entity>((x) => x.roles),
              sorter: false,
              hideInSearch: true,
              ellipsis: true,
              renderText: (_, record) => {
                return (
                  <div>
                    {record.roles?.sort().map((d, dindex) => (
                      <Tag key={dindex} color="geekblue">
                        {d.name}
                      </Tag>
                    ))}
                  </div>
                );
              },
            },
            {
              title: '所属组织',
              width: 120,
              ellipsis: true,
              dataIndex: nameof<Entity>((x) => x.groups),
              renderText: (_, record) => {
                return record.groups?.map((d) => d.name).join(',');
              },
              hideInSearch: true,
            },
            /* {
                 title: '任职岗位',
                 width: 135,
                 ellipsis: true,
                 dataIndex: nameof<Entity>((x) => x.post),
                 hideInSearch: true,
             },*/
            /*{
              title: '性别',
              width: 70,
              dataIndex: nameof<Entity>((x) => x.gender),
              sorter: false,
              filters: undefined,
              hideInSearch: false,
              valueEnum: convertKfEnumsToProTableValueEnum(enumDict['UserGender']),
            },*/
            {
              title: '联系电话',
              width: 135,
              ellipsis: true,
              dataIndex: nameof<Entity>((x) => x.phone),
              hideInSearch: true,
            },
            {
              title: '启用',
              width: 110,
              dataIndex: nameof<Entity>((x) => x.enabled),
              sorter: false,
              filters: undefined,
              formItemProps: {},
              valueEnum: {
                true: { text: '已启用', status: 'Success' },
                false: { text: '未启用', status: 'Error' },
              },
            },
            /*{
                title: '锁定',
                width: 110,
                dataIndex: nameof<Entity>((x) => x.locked),
                sorter: false,
                filters: undefined,
                formItemProps: {
                    allowClear: true,
                },
                valueEnum: {
                    true: {text: '已锁', status: 'Error'},
                    false: {text: '正常', status: 'Success'},
                },
            },*/
            {
              title: '注册时间',
              dataIndex: 'createTimeRange',
              sorter: false,
              hideInTable: true,
              hideInForm: true,
              valueType: 'dateTimeRange',
            },
            {
              title: '注册时间',
              width: 180,
              ellipsis: true,
              dataIndex: nameof<Entity>((x) => x.createTime),
              hideInSearch: false,
              valueType: 'dateTimeRange',
            },
            {
              title: '操作',
              width: 240,
              fixed: 'right',
              dataIndex: 'option',
              valueType: 'option',
              render: (_, record) => (
                <Space size={0} split={<Divider type="vertical" />}>
                  <a onClick={() => actionRef.current?.openFloating.single?.viewModal(record)}>查看</a>
                  {access.hasAnyAuthority('ROLE_ADMIN', 'ROLE_NODE_ADMIN') && (
                    <>
                      {record.id !== '1' && (
                        <>
                          {!record.enabled ? (
                            <a onClick={() => actionRef.current?.executeAction.single?.enableOne(record)}>启用</a>
                          ) : (
                            <a onClick={() => actionRef.current?.executeAction.single?.disableOne(record)}>停用</a>
                          )}
                        </>
                      )}
                      <a onClick={() => actionRef.current?.openFloating.single?.modifyModal(record)}>编辑</a>
                      <a onClick={() => actionRef.current?.openFloating.single?.authListModal(record)}>关联账号</a>
                      {record.id !== '1' && (
                        <>
                          <a onClick={() => actionRef.current?.executeAction.single?.deleteOne(record)}>
                            <Typography.Text type="danger">删除</Typography.Text>
                          </a>
                        </>
                      )}
                    </>
                  )}
                </Space>
              ),
            },
          ]}
        />
      </Layout.Content>
    </Layout>
  );
};

export default EntityTableList;
